package com.example.tool.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created Date 2019/5/15
 *
 * @author liangkun
 * description：json解析器
 */
public class GsonUtil {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }

    /**
     * POST
     * 拼接参数[一个参数，2个参数另写],返回bean
     * okhttp3
     *
     * @return RequestBody
     */
    public static RequestBody getRequestBody(String key, String phone) {
        JSONObject json = new JSONObject();
        try {
            json.put(key, phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return RequestBody.create(MediaType.parse("application/json"), json.toString());
    }
   /**
     * POST
     * 拼接参数[一个参数，2个参数另写],返回bean
     * okhttp3
     *
     * @return RequestBody
     */
    public static RequestBody getRequestBodyCommon(String json) {

        return RequestBody.create(MediaType.parse("application/json"), json);
    }

    /**
     * POST
     * 拼接参数[2个参数],返回bean
     * okhttp3
     *
     * @return RequestBody
     */
    public static RequestBody getRequestDoubleBody(String key, String phone, String keyPassword, String password) {
        JSONObject json = new JSONObject();
        try {
            json.put(key, phone);
            json.put(keyPassword, password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return RequestBody.create(MediaType.parse("application/json"), json.toString());
    }

    /**
     * GET
     * 拼接参数[一个参数，2个参数另写],返回bean
     * okhttp3
     *
     * @return RequestBody
     */
    public static String getOneJson(String key, String phone) {
        JSONObject json = new JSONObject();
        try {
            json.put(key, phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    /**
     * GET
     * 拼接参数[2个参数另写],json
     *
     * @param key       手机参数
     * @param phone     手机号
     * @param parameter 参数
     * @param value     值
     * @return JSON
     */
    public static String getTwoJson(String key, String phone, String parameter, String value) {
        JSONObject json = new JSONObject();
        try {
            json.put(key, phone);
            json.put(parameter, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
}
